import {
  Button,
  Card,
  Col,
  DatePicker,
  Input,
  Pagination,
  Row,
  Select,
  Statistic,
  Table,
  type TableProps,
  Tag,
} from 'antd'
import dayjs from 'dayjs'
import React, { type Key, useEffect, useMemo, useState } from 'react'
import { getBillList } from '../../api/contract'
import { exportToExcel } from '../../utils/export.ts'

interface DataType {
  key?: string
  accountNo: string
  status?: string
  roomNo?: string
  carNo?: string
  tel?: string
  costName1?: string
  costName2?: string
  costName3?: string
  startDate?: string
  endDate?: string
  preferential?: number
  money?: number
  pay?: string
}

export interface QueryType {
  date: string[]
  no: string
  status: string
  page: number
  pageSize: number
}

export default function Bill() {
  const columns: TableProps<DataType>['columns'] = [
    {
      title: 'No.',
      key: 'index',
      render(_value: number, _record: DataType, index) {
        return index + 1
      },
      width: 100,
      // 固定在窗口的最左边，不收左右滚动影响
      fixed: 'left',
    },
    {
      title: '账单号',
      dataIndex: 'accountNo',
      key: 'accountNo',
      width: 150,
    },
    {
      title: '缴费状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render(value: number) {
        return value == 1 ? <Tag color="green">已缴费</Tag> : <Tag color="red">未缴费</Tag>
      },
    },
    {
      title: '房屋号',
      dataIndex: 'roomNo',
      key: 'roomNo',
      width: 100,
    },
    {
      title: '车位号',
      dataIndex: 'carNo',
      key: 'carNo',
      width: 100,
    },
    {
      title: '手机号',
      dataIndex: 'tel',
      key: 'tel',
      width: 150,
    },
    {
      title: '物业费(年)',
      dataIndex: 'costName1',
      key: 'costName1',
      width: 150,
    },

    {
      title: '车位费',
      dataIndex: 'costName2',
      key: 'costName2',
      width: 150,
    },
    {
      title: '房屋租金',
      dataIndex: 'costName3',
      key: 'costName3',
      width: 150,
    },

    {
      title: '开始时间',
      dataIndex: 'startDate',
      key: 'startDate',
      width: 150,
    },
    {
      title: '结束时间',
      dataIndex: 'endDate',
      key: 'endDate',
      width: 150,
    },
    {
      title: '优惠金额',
      dataIndex: 'preferential',
      key: 'preferential',
      width: 150,
    },
    {
      title: '合计应收金额',
      dataIndex: 'money',
      key: 'money',
      width: 150,
    },
    {
      title: '支付方式',
      dataIndex: 'pay',
      key: 'pay',
      width: 100,
    },
    {
      title: '操作',
      width: 230,
      key: 'operate',
      // 固定在窗口的最右边，不收左右滚动影响
      fixed: 'right',
      render() {
        return (
          <>
            <Button type="primary" size="small">
              打印
            </Button>
            <Button type="primary" size="small" danger className="ml mr">
              账单作废
            </Button>
            <Button type="primary" size="small" className="ml">
              退款
            </Button>
          </>
        )
      },
    },
  ]

  const { RangePicker } = DatePicker
  const [dataList, setDataList] = useState<DataType[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [total, setTotal] = useState<number>(0)
  const [pageNumber, setPageNumber] = useState<number>(1)
  const [pageSize, setPageSize] = useState<number>(10)
  const [queryParam, setQueryParam] = useState<QueryType>({ date: [], no: '', page: 0, pageSize: 0, status: '1' })
  const [selectRows, setSelectRows] = useState<Array<DataType>>([])
  const show = useMemo(() => selectRows && selectRows.length <= 0, [selectRows])

  // selectedRowKeys -> 选中行的 key 数组
  // selerctedRows -> 选中行的所有数据的数组
  // info -> 选中行的一些信息
  const handleRowSelectChange = (_selectedRowKeys: Key[], selectedRows: DataType[]) => {
    setSelectRows(selectedRows)
  }

  const rowSelection: TableProps<DataType>['rowSelection'] = {
    // 在切换分页时，保留之前选中的行
    preserveSelectedRowKeys: true,
    onChange: handleRowSelectChange,
  }

  const handlePageChange = (page: number, pageSize: number) => {
    setPageNumber(page)
    setPageSize(pageSize)
  }

  const loadData = async () => {
    setLoading(true)
    const {
      data: { list, total },
    } = await getBillList({ ...queryParam, page: pageNumber, pageSize: pageSize })
    setLoading(false)
    setDataList(list)
    setTotal(total)
  }

  const handleDateChange = (_date: any, dateString: [string, string]) => {
    setQueryParam({
      ...queryParam,
      date: dateString,
    })
  }

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setQueryParam({
      ...queryParam,
      no: e.target.value,
    })
  }

  const handleSelectChange = (value: string) => {
    setQueryParam({
      ...queryParam,
      status: value,
    })
  }

  useEffect(() => {
    loadData()
  }, [pageNumber, pageSize])
  return (
    <div>
      <Card>
        <Row gutter={16}>
          <Col span={6}>
            <Statistic title="应收账单金额" value="16,876.38" />
          </Col>
          <Col span={6}>
            <Statistic title="已缴账单金额" value="6,952.00" />
          </Col>
          <Col span={6}>
            <Statistic title="已退账单金额" value="2,355.23" />
          </Col>
          <Col span={6}>
            <Statistic title="未缴账单金额" value="9,962.00" />
          </Col>
        </Row>
      </Card>

      <Card className="mt">
        <Row gutter={16} className="search">
          <Col span={6}>
            <p>账单日期:</p>
            {/* 最大可选时间不能超过今天 */}
            <RangePicker
              disabledDate={(current) => current && current > dayjs().endOf('day')}
              onChange={handleDateChange}
            />
          </Col>
          <Col span={6}>
            <p>房/车号:</p>
            <Input placeholder="请输入门牌号或者车位号" onChange={handleInputChange} />
          </Col>
          <Col>
            <p>缴费情况:</p>
            <Select
              style={{ width: 120 }}
              defaultValue={'1'}
              options={[
                { value: '1', label: '全部' },
                { value: '2', label: '已缴纳' },
                { value: '3', label: '未缴纳' },
              ]}
              onChange={handleSelectChange}
            />
          </Col>
          <Col span={6}>
            <Button type="primary" onClick={loadData}>
              查询
            </Button>
            <Button className="ml">重置</Button>
          </Col>
        </Row>
      </Card>
      <Card className="mt">
        <Button type="primary" disabled={show} onClick={() => exportToExcel(selectRows, 'export.xlsx')}>
          导出为Excel
        </Button>
        <Button type="primary" danger className="ml" disabled={show}>
          批量作废
        </Button>
      </Card>
      <Card className="mt">
        <Table
          dataSource={dataList}
          columns={columns}
          pagination={false}
          rowKey={(record) => record.accountNo}
          rowSelection={rowSelection}
          scroll={{ x: 'max-content' }}
          loading={loading}
        />
        <Pagination
          className="fr mt"
          showQuickJumper
          current={pageNumber}
          pageSize={pageSize}
          total={total}
          onChange={handlePageChange}
        />
      </Card>
    </div>
  )
}
